package com.vy.stl.controller;

import com.vy.stl.constants.Constants;
import com.vy.stl.entity.Member;
import com.vy.stl.service.MemberService;
import com.vy.stl.util.Result;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @create: 2025/08/29 11:33
 * @description:
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @GetMapping
    public Result getAll(Integer page, Integer limit, Member member) {
        if(ObjectUtils.isEmpty(page) && ObjectUtils.isEmpty(limit)) {
            return Result.success(Constants.STATUS_200,memberService.search(member));
        }
        return Result.success(Constants.STATUS_200,memberService.searchByPage(page,limit,member));
    }

    @PostMapping
    /*@RequestBody注解告诉Spring："请从当前请求的请求体中读取数据，并把它自动转换为参数指定的类型（这里是Member对象）"
    @RequestBody会触发Spring的消息转换器，自动完成：读取请求体中的JSON字符串，将JSON转换为Member类型的Java对象（通过反射匹配属性名），最终将转换后的对象赋值给member参数*/
    public Result add(@RequestBody Member member) throws Exception {
        try {
            memberService.add(member);
            return Result.success(Constants.STATUS_200);
        } catch (Exception e) {
            return Result.error(Constants.ADD_MEMBER_ERROR,e.getMessage());
        }
    }

    @PutMapping
    public Result modify(@RequestBody Member member) throws Exception {
        try {
            int row = memberService.edit(member);
            if(row > 0) {
                return Result.success(Constants.STATUS_200);
            }
            return Result.error(Constants.ADD_MEMBER_ERROR,"会员添加失败");
        }catch (Exception e) {
            return Result.error(Constants.EDIT_MEMBER_ERROR,e.getMessage());

        }
    }

    @DeleteMapping("/{id}")
    public Result remove(@PathVariable("id") Integer id) throws Exception {
//        System.out.println("id:"+id);
        try {
            memberService.remove(id);
            return Result.success(Constants.STATUS_200);
        } catch (Exception e) {
            return Result.error(Constants.REMOVE_MEMBER_ERROR,e.getMessage());
        }
    }
}
